package com.ibeeking.found.uaa.cs.config.advice;

import com.ibeeking.found.common.constants.HeaderNounConstant;
import com.ibeeking.found.uaa.cs.constant.RedisKeyConstant;
import com.ibeeking.nematos.redis.utils.RedisUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author ibeeking
 */
@Component
@Aspect
public class CsAuthTokenAspect {

    @Resource
    private RedisUtils redisUtils;

    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed = pjp.proceed();
        if (null != proceed) {
            ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>) proceed;
            int expiresIn = responseEntity.getBody().getExpiresIn();
            String refreshToken = responseEntity.getBody().getRefreshToken().getValue();
            String jti = responseEntity.getBody().getAdditionalInformation().get(HeaderNounConstant.JWT_JTI).toString().replaceAll("-", "");
            redisUtils.set(RedisKeyConstant.MODULE + RedisKeyConstant.REFRESH_TOKEN + jti, refreshToken, expiresIn - 5);
            return ResponseEntity.status(HttpStatus.OK).body(ResponseResult.success(responseEntity.getBody()));
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ResponseResult.fail(HttpStatus.UNAUTHORIZED.value(), "用户名/密码错误"));
    }
}
